package com.yixq.soa.service.web.auth.service;

import java.util.Calendar;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yixq.soa.service.comm.constant.Constant;
import com.yixq.soa.service.comm.redis.RedisDoorduTemplate;
import com.yixq.soa.service.web.auth.TokenManager;
import com.yixq.soa.service.web.auth.model.TokenModel;

/**
 * token redis manager
 * 
 * @ClassName: RedisTokenManager
 * @Description:
 * @author xiaoqun.yi yixq@doordu.com
 * @date 2017年4月6日 下午5:55:21
 * @version V1.0
 */
@Service
public class RedisTokenManager implements TokenManager {
	protected static final Logger log = LoggerFactory.getLogger(RedisTokenManager.class);
	@Autowired
	private RedisDoorduTemplate redis;

	public boolean checkToken(TokenModel model) {
		if (model == null) {
			return false;
		}
		String tokenKey = tokenKeyPrefix + "_" + model.getToken();
		TokenModel tokenMoel = redis.get(tokenKey);
		if (null==tokenMoel) {
			return false;
		}
		// 如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, Constant.TOKEN_EXPIRES_HOUR);
		redis.set(tokenKey, tokenMoel);
		redis.expireAt(tokenKey, cal.getTime());

		return true;
	}

	public void deleteToken(String appId) {
		String tokenKey = tokenKeyPrefix + appId;
		redis.delete(tokenKey);
	}

	@Override
	public TokenModel createToken(String appId, String appSecret, Integer userId, Integer agentId) {
		// 使用uuid作为源token
		String token = UUID.randomUUID().toString().replace("-", "");
		TokenModel tokenModel = new TokenModel(appId, token, userId, agentId);
		// 存储到redis并设置过期时间
		String tokenKey = tokenKeyPrefix + "_" + token;
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, Constant.TOKEN_EXPIRES_HOUR);
		redis.set(tokenKey, tokenModel);
		redis.expireAt(tokenKey, cal.getTime());
		return tokenModel;
	}

	@Override
	public TokenModel getTokenModelByModel(String token) {
		String tokenKey = tokenKeyPrefix + "_" +token;
		TokenModel tokenMoel = redis.get(tokenKey);
		return tokenMoel;
	}
}